/*
 * 响应过滤器(拦截器)，统一返回体内容
 */

import type { CallHandler, ExecutionContext, NestInterceptor } from '@nestjs/common'
import type { Observable } from 'rxjs'
import { Injectable } from '@nestjs/common'
import { Reflector } from '@nestjs/core'
import { throwError } from 'rxjs'
import { catchError, map } from 'rxjs/operators'

@Injectable()
export class ResponseInterceptor<T> implements NestInterceptor<T, ApiResponseData<T>> {
  constructor(private reflector: Reflector) {}
  intercept(context: ExecutionContext, next: CallHandler): Observable<ApiResponseData<T>> {
    const request = context.switchToHttp().getRequest()
    const formatSms = this.reflector.getAllAndOverride<boolean>('smsSkipFormat', [
      context.getHandler(), // ✅ 方法上的装饰器
      context.getClass(), // ✅ 控制器上的装饰器
    ])
    if (formatSms) {
      return next.handle().pipe(
        map((data: { status: boolean, data: any, message: string }) => {
          const code = data.status ? 0 : 1001
          return {
            path: request.path,
            code,
            msg: data.message,
            data: data.data,
          }
        }),
        catchError(err => throwError(() => err)), // ✅ 保证异常抛回
      )
    }

    return next.handle().pipe(
      map((data) => {
        if (data?.config?.customResponse) {
          return {
            path: request.path,
            code: 0,
            msg: data.msg,
            ...data,
            config: undefined,
          }
        }

        return {
          path: request.path,
          code: 0,
          msg: '操作成功',
          data,
        }
      }),
      catchError((err) => {
        // 直接抛回 Nest 处理
        return throwError(() => err)
      }),
    )
  }
}
